<?php 
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

class ReportAction extends NewzanAction
{
    public function sparkline()
    {
        $adgroup_id = $this->_request( 'adgroup_id');
        $campaign_id = $this->_request('campaign_id');
        $entity = $this->_request('entity');
        $from  = $this->_request('from');
        $to = $this->_request('to');
        //ParamsCheckUtils::checkNumeric($adgroup_id);
        $indicators = array (
                "impressions",
                "click",
                "cost",
                "cpc",
                "click",
                "ctr",
                "cvr",
                "roi",
                "direct_pay",
                "indirect_pay",
                "sales",
                //"direct_pay_count",
                //"indirect_pay_count",
                "fav_shop_count",
                "fav_item_count",
                //"avgpos"
        );

        $from = $from ? $from : date('Y-m-d', time() - 30 * 86400);
        $to = $to ?  $to : date('Y-m-d', time() - 86400);
        if( $campaign_id ){
            $rtpCampaignMdl = new RptCampaignModel();
            $rpt = $rtpCampaignMdl->getAllCampaignsStat($campaign_id ,$indicators ,$from , $to, 'summary,series' );
        }else{
                $rptAdgroupMdl = new RptAdgroupModel;
                $rpt = $rptAdgroupMdl->getAllAdgroupStat( $this->me['user_id'] , $adgroup_id,
                        $indicators, $from , $to, 'summary,series' );
        }
        
        $stats = $this->sparklize($rpt);
        // 设置stats显示的顺序
        $this->order_list = array(
                'impressions',	'cvr',
                'click', 				'ctr',
                'cost', 				'cpc',
                'direct_pay', 	'indirect_pay',
                'sales', 				'roi',
            //    'fav_shop_count', 'fav_item_count',
        );        
        
        $this->stats = $stats;
        $this->display();
    }
    
    protected function sparklize($rpt)
    {
        $labels = RptBaseModel::$LABELS;
        $stats = array();
        $summary = $rpt["summary"];
        foreach( $summary as $k => $v){
            if(isset(RptBaseModel::$LABELS[$k])) { // 只处理统计指标, adgroup_id, campaign_id之类的冗余信息无需处理
                $stats[$k] = array(
                        'num' => ($k=='ctr' || $k=='cvr'? "$v%": $v),
                        'label' => $labels[$k],
                );
                switch( $labels[$k] ){
                    case '销售额':
                    case '直接成交额':
                    case '间接成交额':
                    case '花费':
                        $stats[$k]['css'] = 'orange';
                        $stats[$k]['num'] = '￥' . $stats[$k]['num'];
                        break;
                    default:
                        $stats[$k]['css'] = '';
                        break;
                }
                $stats[$k]['series'] =  join(',', array_column($rpt['series'][ $labels[$k] ], 1));
            }
        }
        return $stats;
    }
    
    
    public function creative()
    {
        $adgroup_id = $this->_request( 'adgroup_id');
        $from  = $this->_request('from');
        $to = $this->_request('to');
        ParamsCheckUtils::checkNumeric($adgroup_id);
        $from = $from ? $from : date('Y-m-d', time() - 30 * 86400);
        $to = $to ?  $to : date('Y-m-d', time() - 86400);
        $creativeMdl = new CreativeModel();
        $creatives = $creativeMdl->getCreativesByAdgroupId($this->me['user_id'], $adgroup_id );
        $rptMdl = new RptAdgroupCreativeModel();
        $order_list = array(
                'cost' , 'sales' , 'cpc' , 
                'impressions' , 'click' , 'ctr'
        ); 
        $this->assign('order_list' , $order_list);
        $html = '';
        foreach($creatives as &$creative){
            $this->assign('unique_id' , 'creative_' . $creative['creative_id']);
            $rpt = $rptMdl->getCreativesStats($this->me['user_id'],$creative['campaign_id'] , $creative['adgroup_id'], $creative['creative_id'] , 'all', $from , $to ,  'summary,series');
            $stats = $this->sparklize($rpt);
            $this->assign('stats' , $stats);
            $html .= $this->fetch('creative');
        }
        echo $html;
    }
    

	public function campaign()
    {
        $from = $this->_request('from');
        $to = $this->_request('to');
        //$indicators = $this->_get("indicators");
        //return all the indicators everytime because any way the model has to read all the data 
		$indicators = 'all';/*  array (
			"impressions",
			"click",
			"cost",
			"cpc",
			"aclick",
			"ctr",
			"cpm",
			"roi",
			"direct_pay",
			"indirect_pay",
			"sales",
			"direct_pay_count",
			"indirect_pay_count",
			"fav_shop_count",
			"fav_item_count",
			"avgpos"
		); */
        $campaign_id = $this->_request('campaign_id');

        if($campaign_id==''||$campaign_id==0){
        	$RptMdl = new RptCustomerModel;
        	$stat = $RptMdl->getAllCustomerStat($indicators , $from , $to );
        }else{
        	$RptMdl = new RptCampaignModel;
        	$stat = $RptMdl->getAllCampaignsStat( $campaign_id , $indicators , $from , $to );
        }

        $compare = $this->_request("compare");
        if($compare == 1){
        	//计算时间差异
        	$day_count = ( strtotime( $to ) - strtotime( $from) ) / 86400;
        	
        	//如果时间超过了90天，选取最多90天
        	if(  date2time( -$day_count * 2)  < date2time(-90) ){
        		$stat['compare'] = array();
        	}else{
        		$compare_from = date('Y-m-d' ,  date2time( -$day_count * 2) );
        		$compare_to = date('Y-m-d' , date2time( -$day_count ) );
        		 
        		if($campaign_id==''||$campaign_id==0){
        			$RptMdl = new RptCustomerModel;
        			 $RptMdl->getAllCustomerStat($indicators , $compare_from , $compare_to );
        		}else{
        			$RptMdl = new RptCampaignModel;
        			$compare_stat = $RptMdl->getAllCampaignsStat( $campaign_id , $indicators , $compare_from , $compare_to );
        		}
        		 
        		//begin comparision
        		$compare_result = array();
        		foreach( $compare_stat['summary'] as $ix => $old_value){
        			$compare_result[$ix] = array();
        			if( $old_value > 0 ){
        				$nu = $stat['summary'][$ix] - $old_value;
        				$compare_result[$ix] = round( $nu / $old_value , 4);
        			}else{
        				$compare_result[$ix] = '--';
        			}
        		}
        		 
        		$stat['compare'] = $compare_result;
        	}
        	
        }
        
    	$this->display_json($stat);
	}

    /**
     * 获取每个计划的报表
     * @param string $value [description]
     */
    public function getcampaigns()
    {
        $display_data = array();
        $me = session('me');
        $from = $this->_request('from');
        $to = $this->_request('to');
        
        $indicators = 'all';
        $compare = $this->_request("compare");

        $RptMdl = new RptCampaignModel;
        $campaignMdl = D("Campaign");

        $campaigns = $campaignMdl->getCampaigns($me['user_id'], false);
        
        foreach ($campaigns as $key => $campaign) {
            $campaign_id = $campaign['campaign_id'];

            $stat = $RptMdl->getAllCampaignsStat( $campaign_id , $indicators , $from , $to );

            
            if($compare == 1){
                //计算时间差异
                $day_count = ( strtotime( $to ) - strtotime( $from) ) / 86400;
                
                //如果时间超过了90天，选取最多90天
                if(  date2time( -$day_count * 2)  < date2time(-90) ){
                    $stat['compare'] = array();
                }else{
                    $compare_from = date('Y-m-d' ,  date2time( -$day_count * 2) );
                    $compare_to = date('Y-m-d' , date2time( -$day_count ) );
                     
                    if($campaign_id==''||$campaign_id==0){
                        $RptMdl = new RptCustomerModel;
                         $RptMdl->getAllCustomerStat($indicators , $compare_from , $compare_to );
                    }else{
                        $RptMdl = new RptCampaignModel;
                        $compare_stat = $RptMdl->getAllCampaignsStat( $campaign_id , $indicators , $compare_from , $compare_to );
                    }
                     
                    //begin comparision
                    $compare_result = array();
                    foreach( $compare_stat['summary'] as $ix => $old_value){
                        $compare_result[$ix] = array();
                        if( $old_value > 0 ){
                            $nu = $stat['summary'][$ix] - $old_value;
                            $compare_result[$ix] = round( $nu / $old_value , 4);
                        }else{
                            $compare_result[$ix] = '--';
                        }
                    }
                     
                    $stat['compare'] = $compare_result;
                }
            }
            $campaigns[$key]['report'] = $stat['summary'];
            $display_data[] = $campaigns[$key];
        }
        $this->display_json($display_data);
    }
	
	/**
	 *  得到一个adgroup或者一个推广计划的通投位置的基础统计数据
	 *  
	 */
	public function placesbase()
    {
		$adgroupRptMdl = new RptAdgroupPlaceModel();
	}
	
	/**
	 * 得到一个推广计划成交关键词数据
	 */
	public function keyword()
    {
		$keywordMdl = new RptKeywordModel();
		$campaign_id = $this->_request('campaign_id');
		$from  = $this->_request('from');
		$to = $this->_request('to');
		ParamsCheckUtils::checkNumeric( $campaign_id , '推广计划ID错误' );
		$from = $from ? $from : date('Y-m-d' , date2time(-90) );
		$to = $to ? $to : date('Y-m-d' , date2time(-1) );
		$filters = array(
				'direct_pay' => array(
					'min' => 1,
					'max' => 100000000
				)
		);
		$keywords = $keywordMdl->getKeywordsByFilters('campaign_id', $campaign_id, 'sales',
				$from ,  $to);
		dump($keywords);
		$this->display_json($keywords);
	}

}
?>